/**
 * Created by zycool on 2016/10/22.
 * 使用html2canvas导出页面成pdf
 */


var canvasPdf = {

    /**
     * 创建隐藏 form 来提交canvas数据
     * @param config
     */
    createForm: function (config, callback) {

        // 创建隐藏iframe
        var dom_iframe = document.createElement('iframe');
        dom_iframe.setAttribute('class', 'hidden');
        dom_iframe.setAttribute('id', 'JQ_hidden_pdf_iframe');
        dom_iframe.setAttribute('name', 'hidden_pdf_iframe');

        // 创建表单
        var url = config.server + '?AjaxMode=true&random=' + Math.random().toString();
        var dom_form = document.createElement('form');
        dom_form.setAttribute('class', 'hidden');
        dom_form.setAttribute('id', 'JQ_hidden_pdf_form');
        dom_form.setAttribute('method', 'post');
        dom_form.setAttribute('action', url);
        dom_form.setAttribute('target', 'hidden_pdf_iframe');

        // 添加数据项
        for (var k in config.param) {
            if (typeof config.param[k] == 'object') {
                if (config.param[k].length) {
                    for (var l = 0, len = config.param[k].length; l < len; l++) {
                        var img_input = document.createElement('input');
                        img_input.setAttribute('type', 'hidden');
                        img_input.setAttribute('name', k);
                        img_input.setAttribute('value', config.param[k][l]);
                        dom_form.appendChild(img_input);
                    }
                }
            } else {
                var dom_input = document.createElement('input');
                dom_input.setAttribute('type', 'hidden');
                dom_input.setAttribute('name', k);
                dom_input.setAttribute('value', config.param[k]);
                dom_form.appendChild(dom_input);
            }
        }

        // 插入表单
        var dom_div = document.getElementById('JQ_export_pdf_div');
        dom_div.innerHTML = '';
        dom_div.innerHTML = dom_iframe.outerHTML + dom_form.outerHTML;

        // 提交
        var dom_idform = document.getElementById('JQ_hidden_pdf_form');
        dom_idform.submit();

        // 获得反馈
        var dom_idiframe = document.getElementById('JQ_hidden_pdf_iframe');
        dom_idiframe.onload = function () {
            var content = this.contentWindow.document.body.innerHTML;
            if (content) {
                try {
                    content = $.parseJSON(content);
                    if (!content.bool) {
                        $(this).MSG({
                            type: 'error',
                            content: content.result,
                            yesBtnAct: DyyBase.goLogin,
                            closeBtnAct: DyyBase.goLogin
                        });
                    }
                } catch (e) {
                    throw new Error(e.message);
                }
            }
        };

        // 最后执行
        if (callback instanceof Function) {
            callback();
            // 影藏加载
            DyyBase.playLoading(false);
        } else {
            DyyBase.playLoading(false);
        }
    },

    /**
     * 导出pdf文件 - 从html内容导出
     * @param config
     */
    exportHtmlPdf: function (config) {

        // 显示加载
        DyyBase.playLoading(true, '请稍等,pdf导出中...');

        var self = this;

        var defaults = {
            dom: '#JQ_pdf_area',
            server: '',
            param: {
                fileName: '',
                name: '',
                imgs: []
            }
        };

        // 写入配置
        if (config) {
            if (Object.prototype.toString.call(config) === '[object Object]') {
                if (config.hasOwnProperty('server')) {
                    defaults.server = config['server'];
                } else {
                    throw new Error('缺少必要的服务信息!');
                }
                if (config.hasOwnProperty('dom')) {
                    defaults.dom = config['dom'];
                } else {
                    throw new Error('缺少必要的dom信息!');
                }
                if (config.hasOwnProperty('param')) {
                    if (config['param'].hasOwnProperty('name')) {
                        defaults.param.name = config['param']['name'];
                    }
                    if (config['param'].hasOwnProperty('imgs')) {
                        defaults.param.imgs = config['param']['imgs'];
                    }
                    if (config['param'].hasOwnProperty('fileName')) {
                        defaults.param.fileName = config['param']['fileName'];
                    }
                }
            }
        } else {
            throw new Error('缺少配置项参数!');
        }

        // 匹配svg内容
        var svg_arr = [];
        var content = defaults.dom.html();
        var reg = /<svg (.+)?<\/svg>/gi;
        var result;
        while ((result = reg.exec(content)) !== null) {
            svg_arr.push(result[0]);
        }

        // 将匹配到的svg内容转化为canvas内容
        var svgs = defaults.dom.find('svg');
        var canids = [];
        if (svg_arr.length && svgs.length) {
            if(svg_arr.length === svgs.length){
                svgs.each(function (i) {
                    var ran_id = (parseInt(Math.random() * 100000)).toString();
                    canids.push(ran_id);
                    var $this = $(this);
                    var $canvas = $('<canvas id="' + ran_id + '"></canvas>');
                    $this.before($canvas);

                    canvg(ran_id, svg_arr[i], {
                        ignoreMouse: true,
                        ignoreAnimation: true
                    });

                    $this.hide();
                });
            }else{
                throw new Error('svg数量不匹配!');
            }
        }

        if (defaults.dom.length > 0) {
            var $area = defaults.dom.find('div.zy-pdf-area');
            if ($area.length > 0) {
                function loadImg(context, index, config) {
                    if (context.eq(index).length) {
                        $(window).scrollTop(context.eq(index).scrollTop());
                        html2canvas(context.eq(index), {
                            onrendered: function (canvas) {
                                defaults.param.imgs.push(canvas.toDataURL('image/png'));
                                loadImg(context, ++index, config);
                            }
                        });
                    } else {
                        self.createForm(config, function () {
                            if (canids.length) {
                                for (var i = 0, len = canids.length; i < len; i++) {
                                    var $cans = $('#' + canids[i]);
                                    if ($cans.length) {
                                        $cans.siblings('svg').show();
                                        $cans.remove();
                                    }
                                }
                            }
                        });
                    }
                }

                loadImg($area, 0, defaults);
            } else {
                $(window).scrollTop(defaults.dom.scrollTop());
                html2canvas(defaults.dom, {
                    onrendered: function (canvas) {
                        defaults.param.imgs = canvas.toDataURL();
                        self.createForm(defaults, function () {
                            if (canids.length) {
                                for (var i = 0, len = canids.length; i < len; i++) {
                                    var $cans = $('#' + canids[i]);
                                    if ($cans.length) {
                                        $cans.siblings('svg').show();
                                        $cans.remove();
                                    }
                                }
                            }
                        });
                    }
                });
            }
        } else {
            throw new Error('没有可导出的pdf区域!');
        }
    }

};
